package com.kfh.ybracelet.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.MyBabyAdapter;
import com.kfh.ybracelet.base.BaseFragment;
import com.kfh.ybracelet.bean.MyResult;
import com.kfh.ybracelet.login.LoginActivity;
import com.kfh.ybracelet.mqtt.MqttManager;
import com.kfh.ybracelet.mqttsource.MqttException;
import com.kfh.ybracelet.my.AboutActivity;
import com.kfh.ybracelet.my.AddBabyActivity;
import com.kfh.ybracelet.my.BabyDetailsActivity;
import com.kfh.ybracelet.my.SettingActivity;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.CircleImageView;
import com.kfh.ybracelet.widget.ListViewForScrollView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * 我的fragment
 * Created by Aaron on 2015/7/20.
 */
public class MyFragement extends BaseFragment implements View.OnClickListener {

    private CircleImageView cv_headpic;
    private List<MyResult.MyData> tempList;
    private MyBabyAdapter myBabyAdapter;
    private Intent mIntent;
    //    private int phoneNum;
    private TextView tv_name;
    private ListViewForScrollView lv_my_baby;
    //    private ListView lv_my_baby;
    private int[] bgPics = {R.mipmap.my_bg_1, R.mipmap.my_bg_2, R.mipmap.my_bg_3, R.mipmap.my_bg_4
            , R.mipmap.my_bg_5, R.mipmap.my_bg_6, R.mipmap.my_bg_7, R.mipmap.my_bg_8};
    private RelativeLayout rl_my_introduce;
    private TextView tv_cache_size;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View myView = View.inflate(getActivity(), R.layout.fragment_my, null);

        tempList = new ArrayList<>();

        initWidget(myView);

        rl_my_introduce.setBackgroundResource(bgPics[new Random().nextInt(8)]);

        return myView;
    }

    @Override
    public void onResume() {
        super.onResume();

        tv_name.setText(sp.getString(Constant.NICKNAME, ""));

        LogUtil.e("tag", " myfragment ===== onresume =====");

        Glide.with(getActivity())
                .load(sp.getString(Constant.USERIMG, ""))
                .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .placeholder(R.mipmap.temp_pic)
                .into(cv_headpic);

        getData();
    }

    private void getData() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取中...", getActivity(), Constant.WEB_ROOT + Constant.MYLIST, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            MyResult myResult = JSONObject.parseObject(str, MyResult.class);
//                            if (Constant.STATUS_SUCCESS == myResult.code) {
                                if (myResult.data != null) {

                                    tempList = myResult.data;
                                    myBabyAdapter.setData(tempList);
                                    myBabyAdapter.notifyDataSetChanged();

                                }
//                            } else {
//                                showToast(Constant.showErrorMsg(myResult.code, getActivity()));
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }
                    }
                }, null);
    }

    private void initWidget(View myView) {

        View headView = View.inflate(getActivity(), R.layout.head_my_fragment, null);

        lv_my_baby = (ListViewForScrollView) myView.findViewById(R.id.lv_my_baby);

        lv_my_baby.addHeaderView(headView);

        rl_my_introduce = (RelativeLayout) headView.findViewById(R.id.rl_my_introduce);
        cv_headpic = (CircleImageView) headView.findViewById(R.id.cv_headpic);
        tv_name = (TextView) headView.findViewById(R.id.tv_name);

        TextView tv_title = (TextView) myView.findViewById(R.id.tv_title);
        tv_cache_size = (TextView) myView.findViewById(R.id.tv_cache_size);
        tv_title.setText(getResources().getString(R.string.my));

        TextView tv_exit = (TextView) myView.findViewById(R.id.tv_exit);

        RelativeLayout rl_clear_cache = (RelativeLayout) myView.findViewById(R.id.rl_clear_cache);

        lv_my_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                --position;
                mIntent = new Intent(getActivity(), BabyDetailsActivity.class);
                if (tempList != null) {
                    mIntent.putExtra("id", tempList.get(position).id);
                    mIntent.putExtra("classInfo", tempList.get(position).classInfo);
                    mIntent.putExtra("level", tempList.get(position).level);
                }
                startActivity(mIntent);
            }
        });


        RelativeLayout rl_add_baby = (RelativeLayout) myView.findViewById(R.id.rl_add_baby);
        RelativeLayout rl_about = (RelativeLayout) myView.findViewById(R.id.rl_about);
//        RelativeLayout rl_version = (RelativeLayout) myView.findViewById(R.id.rl_version);

        rl_my_introduce.setOnClickListener(this);
        rl_add_baby.setOnClickListener(this);
        rl_about.setOnClickListener(this);
//        rl_version.setOnClickListener(this);
        tv_exit.setOnClickListener(this);
        rl_clear_cache.setOnClickListener(this);

//        //版本号
//        tv_version_name.setText(getPackageInfo(getActivity()).versionName);

        myBabyAdapter = new MyBabyAdapter(getActivity(), tempList);
        lv_my_baby.setAdapter(myBabyAdapter);

        setCacheSize();

    }

    //设置缓存文件的大小
    private void setCacheSize() {

        double dirSize = getDirSize(Glide.getPhotoCacheDir(getActivity()));

        LogUtil.e("tag", "缓存图片的大小 : " + dirSize);

        if (dirSize == 0) {
            tv_cache_size.setText("0M");
        } else

            tv_cache_size.setText(dirSize < 1 ? "小于1M" : new DecimalFormat("#.00").format(dirSize) + "M");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rl_my_introduce://进入我的信息修改页面

                mIntent = new Intent(getActivity(), SettingActivity.class);

                startActivity(mIntent);
                break;
            case R.id.rl_about://进入关于页面

                mIntent = new Intent(getActivity(), AboutActivity.class);
                startActivity(mIntent);

                break;

//            case R.id.rl_version://版本
////                showToast("已是最新版本");
//                UmengUpdateAgent.setUpdateOnlyWifi(false);
////                  UmengUpdateAgent.forceUpdate(getActivity());
//
//                UmengUpdateAgent.setUpdateAutoPopup(false);
//                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
//
//                    @Override
//                    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
//                        switch (updateStatus) {
//                            case UpdateStatus.Yes: // has update
//                                UmengUpdateAgent.showUpdateDialog(getActivity(), updateInfo);
//                                break;
//                            case UpdateStatus.No: // has no update
//                                Toast.makeText(getActivity(), "已是最新版本", Toast.LENGTH_SHORT).show();
//                                break;
//                            case UpdateStatus.NoneWifi: // none wifi
//                                Toast.makeText(getActivity(), "没有wifi连接,只在wifi下更新", Toast.LENGTH_SHORT).show();
//                                break;
//                            case UpdateStatus.Timeout: // time out
//                                Toast.makeText(getActivity(), "超时", Toast.LENGTH_SHORT).show();
//                                break;
//                        }
//                    }
//                });
//                UmengUpdateAgent.update(getActivity());
//
//                break;

            case R.id.rl_add_baby://进入添加老人页面

                mIntent = new Intent(getActivity(), AddBabyActivity.class);
                startActivity(mIntent);

                break;
            case R.id.rl_clear_cache://清除缓存

                new ClearTask().execute();

                break;

            case R.id.tv_exit://退出

                quit();

                break;

        }
    }


    private class ClearTask extends AsyncTask<String, String, String> {
        ProgressDialog clearShow;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            clearShow = ProgressDialog.show(getActivity(), Constant.WAIT, "清除中...");
        }

        @Override
        protected String doInBackground(String... params) {
            Glide.get(getActivity()).clearDiskCache();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if (clearShow != null && clearShow.isShowing())
                clearShow.dismiss();

            Glide.get(getActivity()).clearMemory();
            showToast("已清除");

            setCacheSize();
        }
    }


    private double getDirSize(File file) {
        //判断文件是否存在
        if (file.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                double size = 0;
                for (File f : children)
                    size += getDirSize(f);
                return size;
            } else {//如果是文件则直接返回其大小,以“兆”为单位
                double size = (double) file.length() / 1024 / 1024;
                return size;
            }
        } else {
            return 0.0;
        }
    }

    //退出
    private void quit() {

        new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("确定要退出吗?").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Set<String> remaindSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), new LinkedHashSet<String>());
                String userId = sp.getString(Constant.USERID, "");

                //删除用户的数据信息
                sp.edit().clear().apply();
                //保存 消息不提醒的topic至文件中
                CommonUtils.fileSave(Constant.REMAIND + userId, remaindSet);

                dialog.dismiss();

                try {

                    if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                        MqttManager.getInstance().getMqttClient().disconnect();
                } catch (MqttException e) {
                    e.printStackTrace();
                    showToast("退出失败");
                }

                //退出mqtt
                mApplication.exitMqtt();

                //回到登录页面
                mIntent = new Intent(getActivity(), LoginActivity.class);
                startActivity(mIntent);

            }
        }).show();

    }

}
